# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Norman Kosmal (n.kosmal -at- gmx.de)
# All rights reserved.
#
# This software is licensed under Creative Commons 
# Attribution-Noncommercial-No Derivative Works 3.0 Unported License.
# See also: http://creativecommons.org/licenses/by-nc-nd/3.0/

from constants import whois_server, whois_port
from datetime import datetime

def fqdn_lookup(address):
    """
    Try resolve an ip address to a fully qualified 
    domain name using the socket module. Slice off the second level
    domain in order to make a proper whois lookup.
    
    Params:
    address = The ip address to do a fqdn lookup on.
    
    fqdn_lookup(address) -> whois_response
    """
    
    import socket as sock

    data = sock.gethostbyaddr(address)
    fqdn = data[0]
    buffer = fqdn.split(".")
    
    #Get the second level domain and do a whois request.
    domain_name = buffer[len(buffer)-2] + "." + buffer[len(buffer)-1]
    whois_response = whois('-T dn ' + domain_name, whois_server, whois_port)
    return whois_response

def whois(domainname, whoisserver, whoisport):
    """
    Do a whois lookup on the given domain name.
    
    Params:
    domainname  = The domain name to do a whois lookup on
    whoisserver = The whois server to use
    whoisport   = The portnumber the whois server is listening on
                  usually its port 43
                  
    whois(domainname, whoisserver, whoisport) -> response
    """
    
    import socket
    
    response =""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((whoisserver, whoisport))
    sock.send("%s \n\n" % domainname)
    while 1:
        data = sock.recv(2048)
        if not data: break
        response += data
    sock.close()
    return response

def save_whois_lookup(whois_response, file = None):
    """
    Save the generated whois report to a file.
    
    Params:
    dns_response = The whois server`s response.
    file         = The file to save the whois response to.
    
    save_whois_lookup(whois_response, file = None) ->
    """
    
    date = str(datetime.today())
    in_file = open("../output/whois_lookup/whois.log","w")
    in_file.write(whois_response)
    in_file.close()
    return

if __name__ == "__main__":
    whois_response = fqdn_lookup("89.122.29.81") 
    save_whois_lookup(whois_response)
    